# client.py
import tkinter as tk
from tkinter import filedialog, messagebox
import requests
import pandas as pd

class ClientApp:
    def __init__(self, root):
        self.root = root
        self.root.title("老柳家的迷你minitab（客户端）")

        self.file_path = ""
        self.test_type = "选择实验类型"

        self.create_widgets()

    def create_widgets(self):
        self.file_label = tk.Label(self.root, text="选择Excel文件:")
        self.file_label.pack(pady=10)

        self.file_button = tk.Button(self.root, text="浏览", command=self.browse_file)
        self.file_button.pack(pady=5)

        self.test_label = tk.Label(self.root, text="选择测试类型:")
        self.test_label.pack(pady=10)

        self.test_type_var = tk.StringVar(value="实验类型")
        self.test_type_menu = tk.OptionMenu(self.root, self.test_type_var, "正态分布检验", "双T验证", "Anova验证")
        self.test_type_menu.pack(pady=5)

        self.upload_button = tk.Button(self.root, text="上传并测试", command=self.upload_file)
        self.upload_button.pack(pady=20)

    def browse_file(self):
        self.file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx *.xls")])
        if self.file_path:
            self.file_label.config(text=f"已选择文件: {self.file_path}")

    def upload_file(self):
        if not self.file_path:
            messagebox.showerror("错误", "请先选择文件")
            return

        # 读取Excel文件以获取数据（这里只是为了演示，实际上不需要在客户端读取）
        try:
            df = pd.read_excel(self.file_path, sheet_name='Sheet1')
            # 检查必要的列（这里只是为了演示，实际上可以在上传前提示用户）
            if self.test_type_var.get() == "shapiro" and 'A' not in df.columns:
                messagebox.showerror("错误", "Excel文件中必须包含A列")
                return
            if self.test_type_var.get() == "ttest" and ('A' not in df.columns or 'B' not in df.columns):
                messagebox.showerror("错误", "Excel文件中必须包含A列和B列")
                return
            if self.test_type_var.get() == "anova" and ('A' not in df.columns or 'B' not in df.columns or 'C' not in df.columns):
                messagebox.showerror("错误", "Excel文件中必须包含A列，B列和C列")
                return
        except Exception as e:
            messagebox.showerror("错误", f"无法读取Excel文件: {e}")
            return

        # 准备上传的数据
        files = {'file': (self.file_path.split('/')[-1], open(self.file_path, 'rb'))}
        data = {'test_type': self.test_type_var.get()}

        # 发送POST请求到服务器
        try:
            response = requests.post('http://localhost:5000/', files=files, data=data)
            response.raise_for_status()  # 如果请求出错，将引发HTTPError异常
            result = response.text
            messagebox.showinfo("结果", result)
        except requests.exceptions.RequestException as e:
            messagebox.showerror("错误", f"无法连接到服务器: {e}")

if __name__ == "__main__":
    root = tk.Tk()
    app = ClientApp(root)
    root.mainloop()